package com.seabook.store.goodmgr.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.seabook.store.goodmgr.dao.ProductDao;
import com.seabook.store.goodmgr.dao.CategoryDao;
import com.seabook.store.goodmgr.domain.Category;
import com.seabook.store.goodmgr.domain.Product;
import com.seabook.store.util.PropertyManager;

public class ProductServiceImpl implements ProductService {
    private ProductDao productDao;
    private CategoryDao categoryDao;

    public List<Category> getSubCategories(int categoryId) {
        List<Category> categories = categoryDao.getSubCategories(categoryId);
        for (Category c : categories) {
            c.setChildrenCategories(categoryDao.getSubCategories(c.getId()));
        }
        return categories;
    }

    public Category getCategory(int categoryId) {
        return categoryDao.getCategory(categoryId);
    }

    public ProductDao getProductDao() {
        return productDao;
    }

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public CategoryDao getCategoryDao() {
        return categoryDao;
    }

    public void setCategoryDao(CategoryDao categoryDao) {
        this.categoryDao = categoryDao;
    }

    public void saveProduct(Product product) {
        this.productDao.saveOrUpdateProduct(product);
    }

    public List<Product> getProductByCategory(int categoryId) {
        return this.productDao.getProductByCategory(categoryId);
    }

    public Product getProductById(int productId) {
        // TODO Auto-generated method stub
        return this.productDao.getProductById(productId);
    }

    public void saveCategory(Category category) {
        categoryDao.saveCategory(category);

    }

    public boolean deleteCategory(int id) {
        // TODO Auto-generated method stub
        return categoryDao.deleteCategory(id) == 1;
    }

    public String saveProductImage(MultipartFile file, int productId) {
        File imageDir = new File(PropertyManager.getProperty("app.image.location")
                + File.separator + productId);
        File imageFile = new File(imageDir.getAbsolutePath() + File.separator
                + file.getOriginalFilename());
        try {
            if(!imageDir.exists()){
                imageDir.mkdirs();
            }
            file.transferTo(imageFile);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return PropertyManager.getProperty("app.url") + "/image/product/" +productId + "/" + imageFile.getName();
    }
}
